// import { routerRedux } from 'dva/router';
import { message } from 'antd';
import {
  getPayDebtData,
  getProfitData,
  getCashFlowData,
  getGrowAbilitiesData,
  getOperationCapacityData,
} from '@/services/evaluate';
import initChart from '@/utils/initChart';
import { getFinancialOption } from '@/utils/echarts-figures.js';
import { debug } from 'util';

const getServiceAPI = type => {
  switch (type) {
    // 偿债分析
    case 'PayDebt':
      return getPayDebtData;
    // 盈利分析
    case 'Profit':
      return getProfitData;
    // 现金流分析
    case 'CashFlow':
      return getCashFlowData;
    // 成长分析
    case 'GrowAbilities':
      return getGrowAbilitiesData;
    // 营运分析
    case 'OperationCapacity':
      return getOperationCapacityData;

    default:
      return new Error('没有找到对应的数据接口');
  }
};

export default {
  namespace: 'finance',

  state: {
    descs: {},
    charts: [],
    curTabKey: '0',
    curDesc: '',
  },

  effects: {
    *getCharts({ payload }, { call, put }) {
      try {
        // dataType为获取后台数据接口的key
        // descKey为从后台返回数据中获取描述列表的key
        const { dataType, descKey } = payload;
        // 重置左侧tab页选中状态为第一个
        yield put({
          type: 'setData',
          payload: {
            curTabKey: '0',
            curDesc: '',
          },
        });
        const res = yield call(getServiceAPI(dataType), payload);

        if (+res.code === 0 && res.data.charts.length > 0) {
          //设置图表数据
          yield put({
            type: 'setData',
            payload: {
              charts: res.data.charts,
              descs: res.data.desc[descKey],
            },
          });
        } else {
          console.log(e);
          message.error('暂无数据');
        }
      } catch (e) {
        console.log(e);
        message.error('获取数据失败，请稍后再试');
        // yield put({type: "USER_FETCH_FAILED", message: e.message});
      }
    },
    *renderChart({ payload }, { call, put }) {
      const fd = payload.fd;
      if (!fd || !fd.x) {
        return;
      }
      const options = getFinancialOption(
        fd.x, // 除了市值以外的时间横坐标
        fd.self, // 指标
        fd.average, // 行业均值
        fd.yysr, // 营业收入
        fd.yylr, // 营业利润
        fd.market_value // 市值
      );

      console.log('生成的选项：', options);
      initChart(options, payload.chartID);
      //设置指标描述
      yield put({
        type: 'setDesc',
        payload: {
          curDesc: payload.desc,
        },
      });
    },
  },
  reducers: {
    setData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    /**
     * 设置指标解释
     */
    setDesc(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
